"""
Pydantic 数据模型定义
用于API请求和响应的数据验证
"""
from pydantic import BaseModel, Field, field_validator
from typing import Optional, Dict, Any
from datetime import datetime
import re


class UserRegister(BaseModel):
    """用户注册请求模型"""
    username: str = Field(..., min_length=3, max_length=50, description="用户名")
    password: str = Field(..., min_length=6, max_length=100, description="密码")
    email: Optional[str] = Field(None, description="邮箱")
    phone: Optional[str] = Field(None, description="手机号")
    nickname: Optional[str] = Field(None, max_length=100, description="昵称")
    
    @field_validator('email')
    @classmethod
    def validate_email(cls, v):
        """验证邮箱格式"""
        if v is not None and v and v.strip():
            email_pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
            if not re.match(email_pattern, v.strip()):
                raise ValueError('无效的邮箱格式')
        return v.strip() if v else None
    
    @field_validator('phone')
    @classmethod
    def validate_phone(cls, v):
        """验证手机号格式"""
        if v is not None and v and v.strip():
            phone_pattern = r'^1[3-9]\d{9}$'
            if not re.match(phone_pattern, v.strip()):
                raise ValueError('无效的手机号格式')
        return v.strip() if v else None
    
    @field_validator('nickname')
    @classmethod
    def validate_nickname(cls, v):
        """处理昵称"""
        return v.strip() if v else None
    
    class Config:
        json_schema_extra = {
            "example": {
                "username": "test_user",
                "password": "123456",
                "email": "test@example.com",
                "phone": "13800138000",
                "nickname": "测试用户"
            }
        }


class UserLogin(BaseModel):
    """用户登录请求模型"""
    username: str = Field(..., description="用户名/邮箱/手机号")
    password: str = Field(..., min_length=6, description="密码")
    
    class Config:
        json_schema_extra = {
            "example": {
                "username": "test_user",
                "password": "123456"
            }
        }


class UserInfo(BaseModel):
    """用户信息响应模型"""
    id: int
    username: str
    email: Optional[str] = None
    phone: Optional[str] = None
    nickname: Optional[str] = None
    avatar: Optional[str] = None
    role_id: Optional[int] = None
    role_code: Optional[str] = None  # 角色代码，如 platform_kefu, kefu, user 等
    is_verified: bool = False
    created_at: Optional[datetime] = None
    updated_at: Optional[datetime] = None
    last_login: Optional[datetime] = None
    
    class Config:
        from_attributes = True
        json_schema_extra = {
            "example": {
                "id": 1,
                "username": "test_user",
                "email": "test@example.com",
                "phone": "13800138000",
                "nickname": "测试用户",
                "avatar": None,
                "role_id": 1,
                "is_verified": True,
            }
        }


class LoginResponse(BaseModel):
    """登录响应模型"""
    access_token: str
    token_type: str = "bearer"
    user_info: Dict[str, Any]
    
    class Config:
        json_schema_extra = {
            "example": {
                "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
                "token_type": "bearer",
                "user_info": {
                    "id": 1,
                    "username": "test_user",
                    "email": "test@example.com",
                    "phone": "13800138000",
                    "nickname": "测试用户",
                    "avatar": None,
                    "is_active": True,
                    "is_superuser": False,
                    "is_vip": False
                }
            }
        }


class Response(BaseModel):
    """通用响应模型"""
    code: int = 200
    message: str = "success"
    data: Optional[Dict[str, Any]] = None
    
    class Config:
        json_schema_extra = {
            "example": {
                "code": 200,
                "message": "操作成功",
                "data": {}
            }
        }


class DingTalkLoginCallback(BaseModel):
    """钉钉登录回调请求模型"""
    code: str = Field(..., description="钉钉授权码")
    
    class Config:
        json_schema_extra = {
            "example": {
                "code": "abc123def456"
            }
        }


class RoleInfo(BaseModel):
    """角色信息"""
    id: int
    name: str
    code: str
    description: Optional[str] = None
    is_active: bool = True

    class Config:
        from_attributes = True


class SelectRoleRequest(BaseModel):
    """选择角色请求"""
    role_id: int = Field(..., description="角色ID")

    class Config:
        json_schema_extra = {"example": {"role_id": 1}}


class UpdateUserInfoRequest(BaseModel):
    """更新用户信息请求"""
    nickname: Optional[str] = Field(None, max_length=100, description="昵称")
    email: Optional[str] = Field(None, description="邮箱")
    phone: Optional[str] = Field(None, description="手机号")
    avatar: Optional[str] = Field(None, description="头像URL")

    class Config:
        json_schema_extra = {
            "example": {
                "nickname": "新昵称",
                "email": "new@example.com",
                "phone": "13800138000",
                "avatar": "https://example.com/avatar.jpg"
            }
        }


class ChangePasswordRequest(BaseModel):
    """修改密码请求"""
    old_password: str = Field(..., description="原密码")
    new_password: str = Field(..., min_length=6, max_length=100, description="新密码")

    class Config:
        json_schema_extra = {
            "example": {
                "old_password": "123456",
                "new_password": "654321"
            }
        }

# 新增认证schema
class RealNameAuthSchema(BaseModel):
    id: int
    user_id: int
    idcard_image_url: str
    real_name: str
    id_number: str
    address: Optional[str] = None
    created_at: datetime
    class Config:
        from_attributes = True
        json_schema_extra = {
            "example": {
                "id": 1,
                "user_id": 18,
                "idcard_image_url": "http://cdn.xxx.com/abc.png",
                "real_name": "张三",
                "id_number": "410xxx19900909xxxx",
                "address": "广东省深圳市福田区...",
                "created_at": "2024-01-01 11:22:33"
            }
        }
